package com.puff.web.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.puff.core.Puff;
import com.puff.exception.ViewException;

public class ActionView extends View {

	private String actionUrl;
	private static final String contextPath = getContxtPath();
	private static final String contentType = View.ContentType.HTML.getType();
	private Map<String, String> param;

	private static String getContxtPath() {
		String ctx = Puff.getContextPath();
		return ("".equals(ctx) || "/".equals(ctx)) ? null : ctx;
	}

	public Map<String, String> getCarryParam() {
		return param;
	}

	public void setCarryParam(Map<String, String> param) {
		this.param = param;
	}

	public ActionView(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
	}

	public ActionView(String actionUrl) {
		if (contextPath != null && actionUrl.indexOf("://") == -1) {
			actionUrl = contextPath + actionUrl;
		}
		this.actionUrl = actionUrl;
	}

	public ActionView(String actionUrl, Map<String, String> param) {
		this(actionUrl);
		this.param = param;
	}

	public final void put(String name, String value) {
		if (param == null) {
			param = new HashMap<String, String>();
		}
		param.put(name, value);
	}

	public String getActionUrl() {
		return actionUrl;
	}

	@Override
	public void view() {
		StringBuilder html = new StringBuilder(512);
		html.append("<!DOCTYPE html>");
		html.append("<html>");
		html.append("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head>");
		html.append("<body>");
		html.append("<form id=\"__PUFF_ACTION_REDIRECT_FORM\" action=\"");
		html.append(actionUrl);
		html.append("\" ");
		html.append("method=\"POST\">");
		if (param != null && param.size() > 0) {
			for (Entry<String, String> entry : param.entrySet()) {
				html.append("<input type=\"hidden\" ");
				html.append("name=\"");
				html.append(entry.getKey());
				html.append("\" ");
				html.append("value=\"");
				html.append(entry.getValue());
				html.append("\"");
				html.append("/>");
			}
		}
		html.append("</form>");
		html.append("<script>document.getElementById(\"__PUFF_ACTION_REDIRECT_FORM\").submit();</script>");
		html.append("</body>");
		html.append("</html>");
		PrintWriter writer = null;
		try {
			response.setContentType(contentType);
			writer = response.getWriter();
			writer.print(html);
			writer.flush();
		} catch (IOException e) {
			throw new ViewException(e);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

}
